<?php
declare (strict_types = 1);
/**
 * 家
 */
namespace app\admin\controller;

use app\BaseController;
use app\common\facade\admin\HomeAdmin;
use app\common\facade\admin\AdminAdmin;
use think\exception\ValidateException;

class Home extends BaseController
{
    public function login()
    {
        $param = $this->request->post(['username', 'password']);
        try {            
            $this->validate($param, 'app\common\validate\Admin.login');            
            $login = HomeAdmin::login($param);            
        } catch (ValidateException $e) {
            return validateJson($e->getError());
        } catch (\Exception $e) {
            return exceptionJson($e->getMessage(), $e->getCode());
        }

        return successJson($login, '登录成功');
    }

    /**
     * 退出登录
     */
    public function loginOut()
    {
        try {
            HomeAdmin::loginOut();
        } catch (ValidateException $e) {
            return validateJson($e->getError());
        } catch (\Exception $e) {
            return exceptionJson($e->getMessage(), $e->getCode());
        }

        return successJson([], '退出登录成功');
    }
    
    /**
     * 权限【管理员、所有】
     */
    public function ruleAdminAll()
    {

        try {
            $data = AdminAdmin::ruleAdminAll();
        } catch (ValidateException $e) {
            return validateJson($e->getError());
        } catch (\Exception $e) {
            return exceptionJson($e->getMessage(), $e->getCode());
        }

        return successJson($data);
    }

    /**
     * 用户头像上传
     */
    public function upload($id)
    {
        $files[] = $this->request->file('file');
        try {
            validate(['image' => 'filesize:10240|fileExt:jpg|image:200,200,jpg'])->check($files); // 上传的文件校验
            $savename = [];
            foreach($files as $file) {
                $savename[] = \think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
            }
        } catch (\think\exception\ValidateException $e) 
        {
            return validateJson($e->getError());
        }

        return successJson($savename);
    }

    /**
     * 获取token，对应的用户信息
     */
    public function authInfo() {
        
        try {
            $data = HomeAdmin::authInfo();
        } catch (ValidateException $e) {
            return validateJson($e->getError());
        } catch (\Exception $e) {
            return exceptionJson($e->getMessage(), $e->getCode());
        }

        return successJson($data);        
    }
}